# coding=utf-8

import web
import settings

class Connection(object):
	'''数据库对象'''
	def __init__(self):
		self.dbs = {}
	
	'''
		connection.default 的方式获取数据库操作对象
	'''
	def __getattr__(self, key):
		return self._create_db(key)
	
	# TODO: 创建数据库对象
	def _create_db(self, key):
		# 如果已经实例化国了
		if key not in self.dbs:
			# 获取给定数据库配置
			dbsettings = settings.DATABASES.get(key, None)
			if dbsettings:
				db = web.database(dbn = 'mysql'
						, db = dbsettings.NAME
						, user = dbsettings.USER
						, pw = dbsettings.PASSWORD
						, host = dbsettings.HOST
						, port = dbsettings.PORT)
				self.dbs[key] = db
		# 返回结果
		return self.dbs[key]
	
	def dispose(self):
		if self.dbs:
			self.dbs.clear()
